#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char ** argv) {
	if (argc != 2) {
		printf("Niepoprawne wywołanie. Poprawne wywołanie: ./policz <sciezka_do_fifo>\n");
		return -1;
	}
	char * fifo_path = argv[1];
	FILE * fifo;
	FILE * wyniki = fopen("wyniki.log", "w");
	while ((fifo = fopen(fifo_path, "r")) == NULL) {
		sleep(3);
	}
	if (wyniki == NULL) {
		perror("wyniki.log");
		return -3;
	}
	char path[1024];
	int non_zero_count, count, i;
	char buffer[1024];
	while (fscanf(fifo, "%s\n", path) > 0) {
		FILE * file_des = fopen(path, "r");
		if (file_des == NULL) {
			perror(path);
			continue;
		}
		non_zero_count = 0;
		while ((count = fread(buffer, 1, 1024, file_des)) > 0) {
			for (i = 0; i < count; i++) {
				if (buffer[i]) {
					non_zero_count++;
				}
			}
		}
		fclose(file_des);
		if (fprintf(wyniki, "%s: %d\n", path, non_zero_count) < 0) {
			perror("wyniki.log");
		}
		printf("%s: %d\n", path, non_zero_count);
	}
	fclose(fifo);
	fclose(wyniki);
	return 0;
}
